package com.evan.review.architecture.components;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.evan.review.R;
import com.evan.review.architecture.components.viewmodels.CounterViewModel;

/**
 * ViewModel示例Activity
 * 展示ViewModel在配置更改(如屏幕旋转)时保留数据的能力
 */
public class ViewModelExampleActivity extends AppCompatActivity {
    
    private TextView tvCounter;
    private TextView tvInstanceId;
    private TextView tvExplanation;
    private CounterViewModel viewModel;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_model_example);
        
        // 设置标题
        setTitle("ViewModel示例");
        
        // 获取ViewModel实例
        viewModel = new ViewModelProvider(this).get(CounterViewModel.class);
        
        // 初始化视图
        initViews();
        
        // 更新UI
        updateUI();
        
        // 显示ViewModel实例ID
        tvInstanceId.setText("ViewModel实例ID: " + viewModel.getInstanceId());
    }
    
    private void initViews() {
        tvCounter = findViewById(R.id.tv_counter);
        tvInstanceId = findViewById(R.id.tv_instance_id);
        tvExplanation = findViewById(R.id.tv_explanation);
        
        // 增加按钮
        Button btnIncrement = findViewById(R.id.btn_increment);
        btnIncrement.setOnClickListener(v -> {
            viewModel.increment();
            updateUI();
        });
        
        // 减少按钮
        Button btnDecrement = findViewById(R.id.btn_decrement);
        btnDecrement.setOnClickListener(v -> {
            viewModel.decrement();
            updateUI();
        });
        
        // 重置按钮
        Button btnReset = findViewById(R.id.btn_reset);
        btnReset.setOnClickListener(v -> {
            viewModel.reset();
            updateUI();
        });
        
        // 旋转屏幕按钮
        Button btnRotate = findViewById(R.id.btn_rotate);
        btnRotate.setOnClickListener(v -> {
            // 切换屏幕方向
            int currentOrientation = getResources().getConfiguration().orientation;
            if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        });
    }
    
    private void updateUI() {
        tvCounter.setText("计数: " + viewModel.getCounter());
        
        // 更新说明文本
        if (viewModel.getCounter() > 0) {
            tvExplanation.setText("尝试旋转屏幕，计数值将保持不变");
        } else if (viewModel.getCounter() < 0) {
            tvExplanation.setText("ViewModel在配置更改时保留数据");
        } else {
            tvExplanation.setText("点击按钮修改计数值，然后旋转屏幕");
        }
    }
} 